package ch02.Shangji;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class Shangji2 {
    public static void main(String[] args) throws IOException, DocumentException {

        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/ch02/收藏信息.xml"));

        org.dom4j.Element element = document.getRootElement();

        //添加
        org.dom4j.Element brand = element.addElement("Brand");
        brand.addAttribute("name","Vivo");
        org.dom4j.Element type = brand.addElement("Type");
        type.addAttribute("name","X50");
        type.setText("停产了");

        List brand1 = element.elements("Brand");
        for (int i = 0; i < brand1.size(); i++) {
            org.dom4j.Element element1 = (Element) brand1.get(i);
            Attribute name = element1.attribute("name");
            //修改
            if (name.getValue().equals("OPPO")) {
                name.setValue("Vivo");
            }
            //删除
            if (name.getValue().equals("Vivo")){
                element.remove(element1);
            }
        }

        XMLWriter writer = new XMLWriter(new FileWriter("src/ch02/收藏信息.xml"));
        writer.write(document);
        writer.close();
    }
}
